var express = require('express');
var router = express.Router();
var logger = require('../common/logger').logger.getLogger("study_record");
var mysql_query = require('../common/mysql');
var httpresult = require('../common/response');
var moment = require('moment');
const {EE_BADCLOSE} = require("mysql/lib/protocol/constants/errors");
const utils = require("../common/utils");

const EBENHAUS = [0, 0, 1, 2, 3, 4, 5, 1, -99999999]
function formatDate(value) {
    var date = new Date(value);
    var y = date.getFullYear(),
        m = date.getMonth() + 1,
        d = date.getDate(),
        h = date.getHours(),
        i = date.getMinutes(),
        s = date.getSeconds();
    if (m < 10) { m = '0' + m; }
    if (d < 10) { d = '0' + d; }
    if (h < 10) { h = '0' + h; }
    if (i < 10) { i = '0' + i; }
    if (s < 10) { s = '0' + s; }
    var t = y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s;
    return t;
}

/* GET users listing. */
router.post('/add', async function(req, res, next) {
    var [err, data] = await mysql_query(
        "insert into study_record (name, study_count, last_datetime, user_id, question_ids ) value (?, 1, ?, ?, ?)",
        [req.body.name, moment().format('YYYY-MM-DD HH:mm:ss'), req.user_id, req.body.question_ids]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    var result = {
        after_day: EBENHAUS[1],
        study_record_id: data.insertId
    }
    return res.send(httpresult.success(result));
});

router.post('/info', async function(req, res, next) {
    var [err, data] = await mysql_query(
        "select * from study_record where study_record_id = ?",
        [req.body.name, moment().format('YYYY-MM-DD HH:mm:ss'), req.user_id, req.body.study_record_id]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    return res.send(httpresult.success(data));
});
router.post('/update', async function(req, res, next) {
    var [err, data] = await mysql_query(
        "update study_record set study_count = study_count + 1, last_datetime = ? where study_record_id = ? and user_id = ?",
        [moment().format('YYYY-MM-DD HH:mm:ss'), req.body.study_record_id, req.user_id]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    [err, data] = await mysql_query(
        "select * from study_record where study_record_id = ? and user_id = ?",
        [req.body.study_record_id, req.user_id]
    );
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    var result = {
        // after_day 为-1表示完成
        after_day: EBENHAUS[data[0].study_count],
        study_count: data[0].study_count
    }
    return res.send(httpresult.success(result));
});

router.post('/question_list', async function(req, res, next) {
    var [err, data] = await mysql_query(
        "select * from study_record where user_id = ? and study_record_id = ?",
        [req.user_id, req.body.study_record_id]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    let question_ids_str = data[0].question_ids;
    let question_ids = JSON.parse(question_ids_str);
    let sql = "select * from question where 1 = 1 and question_id in (?)";
    [err, data] = await mysql_query(sql, [question_ids]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    for (let id in data) {
        data[id].description = utils.add_src_host(data[id].description)
        data[id].stem = utils.add_src_host(data[id].stem)
        data[id].analysis = utils.add_src_host(data[id].analysis)
        data[id].answer = utils.add_src_host(data[id].answer)
    }
    return res.send(httpresult.success(data));
});

router.post('/list', async function (req, res, next) {
    var [err, data] = await mysql_query(
        "select * from study_record where user_id = ?",
        [req.user_id]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    data = data.sort((a, b) => {
        return a.study_count - b.study_count;
    });

    for(const record of data) {
        // 下一次任务的时间点（上一次任务 + 1天）
        let next_moment = moment(record["last_datetime"]).add(EBENHAUS[record["study_count"]], "days");
        record["next_real_datetime"] = next_moment.format('YYYY-MM-DD HH:mm:ss');
        // 抹平到那一天的0点
        next_moment = moment(next_moment.format('YYYY-MM-DD'));
        // 以datetime方式来展示
        record["next_day"] = next_moment.format('YYYY-MM-DD HH:mm:ss');
        // 距离它还有多少天，向上取整
        record["after_day"] = next_moment.diff(moment(moment().format('YYYY-MM-DD')), "days");
        // if (record["after_day"] < 0) {
        //     record["after_day"] += "(拖延)"
        // }

        // let last_timestamp = new Date(record["last_datetime"]).getTime() / 1000;
        // ebenhaus = EBENHAUS[record["study_count"]] * 86400;
        // let next_timestamp = last_timestamp + ebenhaus;
        // next_timestamp = next_timestamp - next_timestamp % 86400;
        // record["after_day"] = formatDate(next_timestamp * 1000);
        // record["distance_day"] = (next_timestamp - new Date().getTime() / 1000) / 86400;
    }
    return res.send(httpresult.success(data));
});

router.post('/delete', async function(req, res, next) {
    var [err, data] = await mysql_query(
        "delete from study_record where study_record_id = ? and user_id = ?",
        [req.body.study_record_id, req.user_id]);
    if (err) {
        logger.warn(err);
        return res.send(httpresult.sys_error(err));
    }
    return res.send(httpresult.success({}));
});
module.exports = router;
